package touro.mancala.master;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ResponseManager implements Runnable {
	

	private static final Logger logger = Logger.getLogger(ResponseManager.class.getName());
	
	private LinkedBlockingQueue<Response> responses;
	private Server server;
	
	public ResponseManager( Server server ) {
		this.server = server;
		this.responses = new LinkedBlockingQueue<Response>();
	}

	@Override
	public void run() {
		
		
		Map<Integer, Request> requestMap = server.getRequestManager().getRequestsMap();
		Response response = null;
		while ( true ) {
			try {		
				logger.log(Level.INFO,"Waiting for a response");
				response = responses.take();

				logger.log(Level.INFO,"Found response");
				Request request = requestMap.get(response.getId()); 
				
				Socket toClient = request.getToClient();
				
				if(request.processResponse(response)){
					PrintWriter out = new PrintWriter(toClient.getOutputStream());
					Response bestAnswer = request.getBestAnswer();
					out.println( bestAnswer.getMoveNumber() );
					out.flush();
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			finally {
				server.getSlaveManager().addSlave( response.getToSlave() );
			}
			
		}
	}
	
	public void addResponse( Response response ) {
		responses.add(response);
	}
	
}
